<?php
/*
* @Descripttion: 上传文件
* @Author: jiosen <4631458@qq.com>
* @Date: 2024-06-25 11:18:10
*/
namespace app\service;

use think\exception\ValidateException;
use think\facade\Filesystem;

class Upload
{
    private $extensions = [
        'image' => [
            'size'  => 1024 * 1024 * 10,
            'types' => 'jpg,jpeg,png,gif,bmp4'
        ],
        'video' => [
            'size'   => 1024 * 1024 * 50,
            'types'  => 'mp4,avi,wmv,rm,rmvb,mkv'
        ],
        'audio' => [
            'size'   => 1024 * 1024 * 20,
            'types'  => 'mp3,wma,wav'
        ],
        'file'  => [
            'size'  => 1024 * 1024 * 100,
            'types' => 'txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar'
        ]
    ];

    private $type = 'image';

    /**
     * 设置上传类型
     * @param string $type
     * @return $this
     */
    public function type($type)
    {
        if(!empty($type) && isset($this->extensions[$type])){
            $this->type = $type;
        }

        return $this;
    }

    /**
     * 保存文件
     * @param $file
     * @return array
     */
    public function save($file)
    {
        $extensions = $this->extensions[$this->type];

        try {

            validate(['file'=>"fileExt:{$extensions['types']}|fileSize:{$extensions['size']}"])
                ->check(['file'=>$file]);
            $savename = Filesystem::disk('upload')->putFile( 'upload', $file);


        } catch (ValidateException $e) {
            return ['state'=>0,'msg'=>$e->getMessage()];
        }

        // 保存文件信息 todo


        return ['state'=>1,'filename'=>$savename];
    }
    
}
